package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.CourseSchedulingAlways;
import com.xmy.cultivate.service.ICourseSchedulingAlwaysService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.convert.Convert;

import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 日期总排课表，计算缺课使用 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-07-28
 */
@RestController
@RequestMapping("/api/courseSchedulingAlways")
@Scope("prototype")
public class CourseSchedulingAlwaysController {
    @Autowired
    ICourseSchedulingAlwaysService courseSchedulingAlwaysService;

    @Autowired
    ICourseSchedulingAlwaysService iCourseSchedulingAlwaysService;

    @Autowired
    IdWorker idWorker;

    @GetMapping()
    @ApiOperation("查询日期总排课")
    public Result searchScheduling(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<CourseSchedulingAlways> iPage = new Page<>(pageNum, pageSize);

        String num = (String) reMap.get("num");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String gradeSection = (String) reMap.get("gradeSection");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        QueryWrapper queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotBlank(num), "num", num);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(gradeSection), "grade_section", gradeSection);

        if (StringUtils.isNotBlank(startDate)) {
            startDate = startDate.substring(0, 10);
            queryWrapper.ge("start_date", startDate);
        }

        if (StringUtils.isNotBlank(endDate)) {
            endDate = endDate.substring(0, 10);
            queryWrapper.le("end_date", endDate);
        }

        courseSchedulingAlwaysService.page(iPage, queryWrapper);
        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), "查询成功~");
    }

    @PostMapping()
    @ApiOperation("添加日期总排课")
    public Result saveScheduling(@RequestBody Map reMap) {
        String remark = (String) reMap.get("remark");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        List<Object> schedulingList = (List<Object>) reMap.get("schedulingList");

        QueryWrapper queryWrapper = new QueryWrapper<>();
        CourseSchedulingAlways courseSchedulingAlways = new CourseSchedulingAlways();

        courseSchedulingAlways.setRemark(remark);
        if (StringUtils.isNotBlank(yearPart)) {
            courseSchedulingAlways.setYearPart(Integer.valueOf(yearPart));
        }
        if (StringUtils.isNotBlank(quarterNum)) {
            courseSchedulingAlways.setQuarterNum(Integer.valueOf(quarterNum));
        }

        for (Object object : schedulingList) {
            String jsonObject = JSON.toJSONString(object);
            //将json转成需要的对象
            CourseSchedulingAlways schedulingAlways = JSONObject.parseObject(jsonObject, CourseSchedulingAlways.class);

            courseSchedulingAlways.setNum(schedulingAlways.getNum());
            courseSchedulingAlways.setRemark(schedulingAlways.getRemark());
            courseSchedulingAlways.setGradeSection(schedulingAlways.getGradeSection());
            courseSchedulingAlways.setStartDate(schedulingAlways.getStartDate());
            courseSchedulingAlways.setEndDate(schedulingAlways.getEndDate());

            String name = Convert.numberToChinese(schedulingAlways.getNum(), false);
            //范围在10和19内，前面会多出“一”字符，例如12转换为一十二，为了便于观看去掉第一个字符
            if (schedulingAlways.getNum() >= 10 && schedulingAlways.getNum() <= 19) {
                name = name.substring(1);
            }
            name = "第" + name + "课次";
            courseSchedulingAlways.setName(name);

            queryWrapper.clear();
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("num", schedulingAlways.getNum());
            queryWrapper.eq("grade_section", schedulingAlways.getGradeSection());
            List<CourseSchedulingAlways> always = courseSchedulingAlwaysService.list(queryWrapper);
            if (always.size() != 0) {
                Map<String, String> map = new HashMap<>();
                map.put("num", String.valueOf(schedulingAlways.getNum()));
                map.put("name", name);
                return new Result(Code.SAVE_ERROR, map, "已存在" + name + "排课信息，不能重复添加~");
            }

            courseSchedulingAlways.setId(idWorker.nextId());
            courseSchedulingAlwaysService.save(courseSchedulingAlways);
        }
        return new Result(Code.SAVE_OK, "", Code.SAVE_OK_MSG);
    }

    @DeleteMapping()
    @ApiOperation("删除日期总排课")
    public Result removeScheduling(@RequestParam("id") String id) {
        CourseSchedulingAlways eduTask = courseSchedulingAlwaysService.getById(id);
        if (Objects.isNull(eduTask)) {
            return new Result(Code.DELETE_ERROR, Code.DELETE_ERROR_MSG, "暂无该排课信息~");
        }
        Boolean remove = courseSchedulingAlwaysService.removeById(id);
        return new Result(remove ? Code.DELETE_OK : Code.DELETE_ERROR, "", remove ? Code.DELETE_OK_MSG : Code.DELETE_ERROR_MSG);
    }

    @PostMapping("/updateScheduling")
    @ApiOperation("修改日期总排课")
    public Result updateScheduling(@RequestBody Map reMap) {
        String id = (String) reMap.get("id");
        String remark = (String) reMap.get("remark");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String num = (String) reMap.get("num");
        String gradeSection = (String) reMap.get("gradeSection");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysService.getById(id);

        if (Objects.isNull(courseSchedulingAlways)) {
            return new Result(Code.UPDATE_ERROR, Code.UPDATE_ERROR_MSG, "暂无该排课信息，修改失败~");
        }

        courseSchedulingAlways.setRemark(remark);
        if (StringUtils.isNotBlank(yearPart)) {
            courseSchedulingAlways.setYearPart(Integer.valueOf(yearPart));
        }
        if (StringUtils.isNotBlank(quarterNum)) {
            courseSchedulingAlways.setQuarterNum(Integer.valueOf(quarterNum));
        }
        if (StringUtils.isNotBlank(num)) {
            courseSchedulingAlways.setNum(Integer.valueOf(num));
            String name = Convert.numberToChinese(Integer.valueOf(num), false);
            //范围在10和19内，前面会多出“一”字符，例如12转换为一十二，为了便于观看去掉第一个字符
            if (Integer.valueOf(num) >= 10 && Integer.valueOf(num) <= 19) {
                name = name.substring(1);
            }
            name = "第" + name + "课次";
            courseSchedulingAlways.setName(name);
        }
        if (StringUtils.isNotBlank(gradeSection)) {
            courseSchedulingAlways.setGradeSection(Integer.valueOf(gradeSection));
        }
        if (StringUtils.isNotBlank(startDate)) {
            startDate = startDate.substring(0, 10);
            courseSchedulingAlways.setStartDate(LocalDate.parse(startDate));
        }
        if (StringUtils.isNotBlank(endDate)) {
            endDate = endDate.substring(0, 10);
            courseSchedulingAlways.setEndDate(LocalDate.parse(endDate));
        }
        courseSchedulingAlwaysService.updateById(courseSchedulingAlways);
        return new Result(Code.UPDATE_OK, "", "修改成功~");
    }

    @GetMapping("/getNowLessonNum")
    public Result getNowLessonNum(){
        LocalDate nowLocalDate = LocalDate.now();
        QueryWrapper<CourseSchedulingAlways> courseSchedulingAlwaysQueryWrapper = new QueryWrapper<>();
        courseSchedulingAlwaysQueryWrapper.le("start_date",nowLocalDate);
        courseSchedulingAlwaysQueryWrapper.ge("end_date",nowLocalDate);
        courseSchedulingAlwaysQueryWrapper.orderByAsc("num");
        courseSchedulingAlwaysQueryWrapper.last("limit 1");
        CourseSchedulingAlways courseSchedulingAlways = iCourseSchedulingAlwaysService.getOne(courseSchedulingAlwaysQueryWrapper);
        Integer lessonNum = 0;
        if (courseSchedulingAlways!=null){
            lessonNum = courseSchedulingAlways.getNum();
        }

        return new Result(Code.OK, lessonNum, "获取成功");
    }
}
